"""
模型状态汇报API路由
处理客户端模型状态汇报和查询
"""

import time
import uuid
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query
from ..models import ModelStatusReport, ModelStatusResponse
from ..storage import data_manager, ModelStatusInfo

router = APIRouter(prefix="/model-status", tags=["model-status"])


@router.post("/report", response_model=ModelStatusResponse)
async def report_model_status(report: ModelStatusReport):
    """
    汇报模型状态
    客户端调用此接口汇报本地模型的状态信息
    """
    try:
        # 生成状态ID
        status_id = str(uuid.uuid4())
        current_time = time.time()
        
        # 创建模型状态信息
        model_status = ModelStatusInfo(
            id=status_id,
            client_id=report.client_id,
            model_name=report.model_name,
            model_type=report.model_type,
            model_size=report.model_size,
            model_version=report.model_version,
            status=report.status,
            file_path=report.file_path,
            file_size=report.file_size,
            upload_time=report.upload_time,
            last_used=report.last_used,
            usage_count=report.usage_count,
            performance_metrics=report.performance_metrics,
            error_message=report.error_message,
            system_info=report.system_info,
            reported_at=current_time,
            last_updated=current_time
        )
        
        # 检查是否已存在相同的模型状态（同一客户端的同一模型）
        existing_statuses = await data_manager.get_model_statuses_by_client(report.client_id)
        existing_status = None
        for status in existing_statuses:
            if (status.model_name == report.model_name and 
                status.model_type == report.model_type):
                existing_status = status
                break
        
        if existing_status:
            # 更新现有状态
            existing_status.model_size = report.model_size
            existing_status.model_version = report.model_version
            existing_status.status = report.status
            existing_status.file_path = report.file_path
            existing_status.file_size = report.file_size
            existing_status.upload_time = report.upload_time
            existing_status.last_used = report.last_used
            existing_status.usage_count = report.usage_count
            existing_status.performance_metrics = report.performance_metrics
            existing_status.error_message = report.error_message
            existing_status.system_info = report.system_info
            existing_status.last_updated = current_time
            
            await data_manager.update_model_status(existing_status)
            message = f"模型状态已更新: {report.model_name}"
        else:
            # 添加新状态
            await data_manager.add_model_status(model_status)
            message = f"模型状态已记录: {report.model_name}"
        
        return ModelStatusResponse(
            success=True,
            message=message,
            reported_at=current_time
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"汇报模型状态失败: {str(e)}")


@router.get("/client/{client_id}")
async def get_client_model_statuses(
    client_id: str,
    model_name: Optional[str] = Query(None, description="模型名称过滤"),
    model_type: Optional[str] = Query(None, description="模型类型过滤"),
    status: Optional[str] = Query(None, description="状态过滤")
):
    """
    获取客户端的模型状态列表
    """
    try:
        model_statuses = await data_manager.get_model_statuses_by_client(client_id)
        
        # 应用过滤条件
        if model_name:
            model_statuses = [s for s in model_statuses if model_name.lower() in s.model_name.lower()]
        if model_type:
            model_statuses = [s for s in model_statuses if s.model_type == model_type]
        if status:
            model_statuses = [s for s in model_statuses if s.status == status]
        
        return {
            "success": True,
            "client_id": client_id,
            "model_statuses": [status.to_dict() for status in model_statuses],
            "total": len(model_statuses),
            "timestamp": time.time()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取客户端模型状态失败: {str(e)}")


@router.get("/all")
async def get_all_model_statuses(
    client_id: Optional[str] = Query(None, description="客户端ID过滤"),
    model_name: Optional[str] = Query(None, description="模型名称过滤"),
    model_type: Optional[str] = Query(None, description="模型类型过滤"),
    status: Optional[str] = Query(None, description="状态过滤"),
    limit: int = Query(100, ge=1, le=1000, description="返回数量限制"),
    offset: int = Query(0, ge=0, description="偏移量")
):
    """
    获取所有模型状态（管理员接口）
    """
    try:
        model_statuses = await data_manager.get_model_statuses()
        
        # 应用过滤条件
        if client_id:
            model_statuses = [s for s in model_statuses if s.client_id == client_id]
        if model_name:
            model_statuses = [s for s in model_statuses if model_name.lower() in s.model_name.lower()]
        if model_type:
            model_statuses = [s for s in model_statuses if s.model_type == model_type]
        if status:
            model_statuses = [s for s in model_statuses if s.status == status]
        
        # 分页
        total = len(model_statuses)
        model_statuses = model_statuses[offset:offset + limit]
        
        return {
            "success": True,
            "model_statuses": [status.to_dict() for status in model_statuses],
            "total": total,
            "limit": limit,
            "offset": offset,
            "timestamp": time.time()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模型状态失败: {str(e)}")


@router.get("/statistics")
async def get_model_status_statistics():
    """
    获取模型状态统计信息
    """
    try:
        model_statuses = await data_manager.get_model_statuses()
        
        # 统计信息
        total_models = len(model_statuses)
        status_counts = {}
        type_counts = {}
        client_counts = {}
        
        for status in model_statuses:
            # 状态统计
            status_counts[status.status] = status_counts.get(status.status, 0) + 1
            
            # 类型统计
            type_counts[status.model_type] = type_counts.get(status.model_type, 0) + 1
            
            # 客户端统计
            client_counts[status.client_id] = client_counts.get(status.client_id, 0) + 1
        
        return {
            "success": True,
            "statistics": {
                "total_models": total_models,
                "status_distribution": status_counts,
                "type_distribution": type_counts,
                "client_distribution": client_counts,
                "unique_clients": len(client_counts),
                "unique_models": len(set(f"{s.model_name}_{s.model_type}" for s in model_statuses))
            },
            "timestamp": time.time()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")


@router.delete("/client/{client_id}")
async def clear_client_model_statuses(client_id: str):
    """
    清除客户端的模型状态（管理员接口）
    """
    try:
        await data_manager.delete_model_statuses_by_client(client_id)
        
        return {
            "success": True,
            "message": f"已清除客户端 {client_id} 的所有模型状态",
            "timestamp": time.time()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"清除客户端模型状态失败: {str(e)}")


@router.delete("/{status_id}")
async def delete_model_status(status_id: str):
    """
    删除指定的模型状态（管理员接口）
    """
    try:
        await data_manager.delete_model_status(status_id)
        
        return {
            "success": True,
            "message": f"已删除模型状态 {status_id}",
            "timestamp": time.time()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除模型状态失败: {str(e)}")
